import React, { Component } from 'react'
import { render } from 'react-dom'
import { Router, Route, Link, createHyBrowserHistory } from 'yo-router'

// 创建历史
const browserHistory = createHyBrowserHistory()

const App = ({ children }) => <div>{children}</div>
const About = () => <div>About</div>
const NoMatch = () => <div>No Match!</div>

const Users = ({ children }) => (
  <div>
    <h1>Users</h1>
    <div className="master">
      <ul>
        {/* 使用 <Link> 标签进行方便的路由跳转 */}
        {this.state.users.map(user => (
          <li key={user.id}><Link to={`/user/${user.id}`}>{user.name}</Link></li>
        ))}
      </ul>
    </div>
    <div className="detail">
      {children}
    </div>
  </div>
)

class User extends Component {
  componentDidMount() {
    this.setState({
      // 对应页面内的组件将会获取 URL 参数，以便进行数据的获取和渲染
      user: findUserById(this.props.params.userId)
    })
  }

  render() {
    return (
      <div>
        <h2>{this.state.user.name}</h2>
      </div>
    )
  }
}

// 声明路由配置
render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="about" component={About}/>
      <Route path="users" component={Users}>
        <Route path="/user/:userId" component={User}/>
      </Route>
      <Route path="*" component={NoMatch}/>
    </Route>
  </Router>
), document.getElementById('root'))